/**
 * 库存查询汇总相关js文件
 */
var stockGoodsList = {};
var $stockGoodsTable = null;
stockGoodsList.operation = {};

var $contentIframe = null;

// 页面初始化
$(function() {
    setPageElementStatus("stockGoodsCheckList");
    // 店铺列表初始化
    stockGoodsList.initShopList();

    stockGoodsList.initStockGoodsTable();

    // 按钮绑定
    $("#btnQuickSearch").unbind("click").bind("click", stockGoodsList.queryTableData);

    // 快速查询回车
    $('#quickSearch').keydown(function(e){
        if (e.keyCode == 13&&$('#btnQuickSearch').is(":visible")) {

            $('#btnQuickSearch').click();
        }
    });

    $(window.top.window).resize(function(){
        var swidth = $("div.tab-content").width()-30;
        var iframeDom = $("div.tab-content").find("iframe:visible");
        ;
        if(iframeDom.length>0){
            iframeDom.eq(0).width(Number(swidth));
        }
    });

    // 店铺导出关闭事件发生
    $('#exportList').on('hide.bs.modal', function () {
        // 父窗体归还本页的编辑对话框
        window.top.window.returnCustomModalDialog();
    })

    // 店铺导出，导出按钮点击事件绑定
    $("#btnExportList").click(function(){
        exportStock();
    });

    // 店铺导出关闭事件发生
    $('#exportList').on('shown.bs.modal', function () {
        // 父窗体归还本页的编辑对话框
        window.top.window.$("#select-all").click();
    })

    $("#storSelect").change(function(){
        tableColNm=new Array();
        tableColVal=new Array();

        window.top.window.$("#public-methods").html('');
        if ("p"==window.top.window.$("#storSelect").val()){
            window.top.window.$("#public-methods").append('<option value="goodsCode">商品商家编码</option>');
            window.top.window.$("#public-methods").append('<option value="goodsName">商品名称</option>');
            window.top.window.$("#public-methods").append('<option value="totalQty">本地总库存数</option>');
            window.top.window.$("#public-methods").append('<option value="stockQty">本地合格品数</option>');
            window.top.window.$("#public-methods").append('<option value="available">可用数</option>');
            window.top.window.$("#public-methods").append('<option value="canallotQty">可分派数</option>');
            window.top.window.$("#public-methods").append('<option value="allotQty">已分派数</option>');
            window.top.window.$("#public-methods").append('<option value="unallotQty">未分派数</option>');
            window.top.window.$("#public-methods").append('<option value="logicStockoutQty">逻辑出库数</option>');
            window.top.window.$("#public-methods").append('<option value="onwayQty">在途数</option>');
            window.top.window.$("#public-methods").append('<option value="reserveQty">预留数</option>');
            window.top.window.$("#public-methods").append('<option value="junkQty">废品数</option>');
            window.top.window.$("#public-methods").append('<option value="totalCount">第三方总库存数</option>');
            window.top.window.$("#public-methods").append('<option value="sellCount">第三方可销售库存数</option>');
            window.top.window.$("#public-methods").append('<option value="junkCount">第三方废品数</option>');
        } else {
            window.top.window.$("#public-methods").append('<option value="goodsCode">商品商家编码</option>');
            window.top.window.$("#public-methods").append('<option value="goodsName">商品名称</option>');
            window.top.window.$("#public-methods").append('<option value="storName">仓库名称</option>');
            window.top.window.$("#public-methods").append('<option value="totalQty">本地仓库总库存数</option>');
            window.top.window.$("#public-methods").append('<option value="stockQty">本地仓库正品数</option>');
            window.top.window.$("#public-methods").append('<option value="junkQty">本地仓库次品数</option>');
            window.top.window.$("#public-methods").append('<option value="available">本地仓库可用数</option>');
            window.top.window.$("#public-methods").append('<option value="allotQty">本地仓库已分派数</option>');
            window.top.window.$("#public-methods").append('<option value="unallotQty">本地仓库未分派数</option>');
            window.top.window.$("#public-methods").append('<option value="logicStockoutQty">本地仓库逻辑出库数</option>');
            window.top.window.$("#public-methods").append('<option value="onwayQty">本地仓库在途数</option>');
            window.top.window.$("#public-methods").append('<option value="reserveQty">本地仓库预留数</option>');

            window.top.window.$("#public-methods").append('<option value="extTotalCount">第三方仓库总库存数</option>');
            window.top.window.$("#public-methods").append('<option value="extstorStockCount">第三方仓库正品数</option>');
            window.top.window.$("#public-methods").append('<option value="extstorJunkCount">第三方仓库次品数</option>');
            window.top.window.$("#public-methods").append('<option value="extstorSellCount">第三方仓库可销售数</option>');
            window.top.window.$("#public-methods").append('<option value="extstorAvailable">第三方仓库可用数</option>');
            window.top.window.$("#public-methods").append('<option value="extstorAllotQty">第三方仓库已分派数</option>');
            window.top.window.$("#public-methods").append('<option value="extstorUnallotQty">第三方仓库未分派数</option>');
            window.top.window.$("#public-methods").append('<option value="extstorCanallotQty">第三方仓库可分派数</option>');
            window.top.window.$("#public-methods").append('<option value="extstorOnwayQty">第三方仓库在途数</option>');
            window.top.window.$("#public-methods").append('<option value="extstorReserveQty">第三方仓库预留数</option>');
        }

        window.top.window.$("#public-methods option").each(function (){
            tableColNm.push($(this).text());
            tableColVal.push($(this).val());
        });

        //刷新隐藏的select项目，将新的option显示到画面上
        window.top.window.$('#public-methods').multiSelect('refresh');

        window.top.window.$("#select-all").click();

        //清空frame的SRC，相当于重置
        window.top.window.$('#exportFrame').attr('src', '');
    });
});

// 初始化项目列表控件
stockGoodsList.initShopList = function(){
    var prjShopList = stockGoodsList.operation.getPrjShopList();
    var optionTemplate = "";
    var tempItem = "";
    for(var i=0,j=prjShopList.length;i<j;i++){
        tempItem = prjShopList[i];
        optionTemplate = '<option value="'+tempItem.shopId+'">'+tempItem.shopName+'</option>';
        $(".selectShop").append($(optionTemplate));
    }
};

stockGoodsList.operation.getPrjShopList = function(){
    var returnData = {};
    $.ajax({
        type : "GET",
        url : "/shop/unpagedShopList.action",
        contentType : "application/json;charset=utf-8",
        dataType : "json",
        async : false,
        success : function(data) {
            if (data.result == "success") {
                returnData = data.data;
            } else {
                window.top.window.showModalAlert("项目店铺获取失败，原因是："+data.message);
            }
        },
        error : function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert("项目店铺获取失败");
            }
        }
    });
    return returnData;
}


// 初始化系统退款单列表
stockGoodsList.initStockGoodsTable = function() {
    $stockGoodsTable = $("#stockGoodsTable")
        .DataTable(
            {
                "processing" : true,
                "serverSide" : true,
                "lengthMenu" : [ [ 10, 25, 50, 100, 500, 1000 ], [ 10, 25, 50, 100,500,1000 ] ],
                "dom" : '<"bottom"rtflp>',
                "searching" : false,
                "scrollX" : true,
                "scrollY" : "410px",
                // "scrollCollapse": true,
                // "destroy" : true,
                "pagingType" : "full_numbers",
                "deferRender" : true,
                "ajax" : {
                    "url" : "/stockGoods/getStockGoodsInfo.action",
                    "type" : "get",
                    "data" : function(d) {
                        d.quickSearch = encodeURI($("#quickSearch").val());

                    }
                },
                "columns" : [ {
                    "data" : "sonShow",
                    "orderable" : false
                }, {
                    "data" : "goodsCode",
                    "orderable" : true
                }, {
                    "data" : "goodsName",
                    "orderable" : true,
                }, {
                    "data" : "totalQty",
                    "orderable" : true,
                }, {
                    "data" : "stockQty",
                    "orderable" : true
                }, {
                    "data" : "available",
                    "orderable" : true
                }, {
                    "data" : "canallotQty",
                    "orderable" : true
                }, {
                    "data" : "allotQty",
                    "orderable" : true
                }, {
                    "data" : "unallotQty",
                    "orderable" : true
                }, {
                    "data" : "logicStockoutQty",
                    "orderable" : true
                }, {
                    "data" : "onwayQty",
                    "orderable" : true
                }, {
                    "data" : "reserveQty",
                    "orderable" : true
                }, {
                    "data" : "junkQty",
                    "orderable" : true
                }, {
                    "data" : "totalCount",
                    "orderable" : true
                }, {
                    "data" : "sellCount",
                    "orderable" : true
                }, {
                    "data" : "junkCount",
                    "orderable" : true
                } ],
                "columnDefs" : [ {
                    "className" : "truncate-text tooltip-column-detail text-left",
                    "targets" : [ 1 ]
                },{
                    "className" : "truncate-text tooltip-column-detail text-left",
                    "targets" : [ 2 ]
                },{
                    "className" : "truncate-text tooltip-column-detail text-left",
                    "targets" : [ 3 ]
                },{
                    "className" : "truncate-text tooltip-column-detail text-left",
                    "targets" : [ 4 ]
                },{
                    "className" : "truncate-text tooltip-column-detail text-right",
                    "targets" : [ 5 ]
                },{
                    "className" : "truncate-text tooltip-column-detail text-right",
                    "targets" : [ 6 ]
                },{
                    "className" : "truncate-text tooltip-column-detail text-right",
                    "targets" : [ 7 ]
                },{
                    "className" : "truncate-text tooltip-column-detail text-right",
                    "targets" : [ 8 ]
                },{
                    "className" : "truncate-text tooltip-column-detail text-right",
                    "targets" : [ 9 ]
                },{
                    "className" : "truncate-text tooltip-column-detail text-right",
                    "targets" : [ 10 ]
                },{
                    "className" : "truncate-text tooltip-column-detail text-right",
                    "targets" : [ 11 ]
                },{
                    "className" : "truncate-text tooltip-column-detail text-right",
                    "targets" : [ 12 ]
                },{
                    "className" : "truncate-text tooltip-column-detail text-right",
                    "targets" : [ 13 ]
                },{
                    "className" : "truncate-text tooltip-column-detail text-right",
                    "targets" : [ 14 ]
                },{
                    "className" : "truncate-text tooltip-column-detail text-right",
                    "targets" : [ 15 ]
                } ],
                "order" : [ [ 1, "asc" ] ],
                "footerCallback": function (tfoot, data, start, end, display) {
                    var api = this.api();
                    $( api.column( 3 ).footer() ).html(
                        api.column( 3 ).data().reduce( function ( a, b ) {
                            return a + b;
                        }, 0 )
                    );
                    $( api.column( 4 ).footer() ).html(
                        api.column( 4 ).data().reduce( function ( a, b ) {
                            return a + b;
                        }, 0 )
                    );
                    $( api.column( 5 ).footer() ).html(
                        api.column( 5 ).data().reduce( function ( a, b ) {
                            return a + b;
                        }, 0 )
                    );
                    $( api.column( 6 ).footer() ).html(
                        api.column( 6 ).data().reduce( function ( a, b ) {
                            return a + b;
                        }, 0 )
                    );
                    $( api.column( 7 ).footer() ).html(
                        api.column( 7 ).data().reduce( function ( a, b ) {
                            return a + b;
                        }, 0 )
                    );
                    $( api.column( 8 ).footer() ).html(
                        api.column( 8 ).data().reduce( function ( a, b ) {
                            return a + b;
                        }, 0 )
                    );
                    $( api.column( 9 ).footer() ).html(
                        api.column( 9 ).data().reduce( function ( a, b ) {
                            return a + b;
                        }, 0 )
                    );
                    $( api.column( 10 ).footer() ).html(
                        api.column( 10 ).data().reduce( function ( a, b ) {
                            return a + b;
                        }, 0 )
                    );
                    $( api.column( 11 ).footer() ).html(
                        api.column( 11 ).data().reduce( function ( a, b ) {
                            return a + b;
                        }, 0 )
                    );
                    $( api.column( 12 ).footer() ).html(
                        api.column( 12 ).data().reduce( function ( a, b ) {
                            return a + b;
                        }, 0 )
                    );
                    $( api.column( 13 ).footer() ).html(
                        api.column( 13 ).data().reduce( function ( a, b ) {
                            return a + b;
                        }, 0 )
                    );
                    $( api.column( 14 ).footer() ).html(
                        api.column( 14 ).data().reduce( function ( a, b ) {
                            return a + b;
                        }, 0 )
                    );
                    $( api.column( 15 ).footer() ).html(
                        api.column( 15 ).data().reduce( function ( a, b ) {
                            return a + b;
                        }, 0 )
                    );
                },
            })
        .on(
            'draw.dt',
            function() {
                //解决因滚动条导致的列对不齐问题
                // $(".dataTables_scrollBody").css("overflow-y","overlay");
                // 以下注释部分是用于固定列调整样式用的，需要固定列时打开下面代码
                // setTimeout(function() {
                //     var rightWidth = $('#stockGoodsTable_wrapper').find("div.DTFC_RightBodyLiner").width();
                //     var leftWidth = $('#stockGoodsTable_wrapper').find("div.DTFC_LeftBodyLiner").width();
                //
                //     $('#stockGoodsTable_wrapper').find("div.DTFC_LeftBodyLiner").width(leftWidth + 4);
                //     $('#stockGoodsTable_wrapper').find("div.DTFC_RightBodyLiner").width(rightWidth + 4);
                // }, 1);
                // $("table").find("th.sorting_asc").removeClass("sorting_asc");
                // 表格绘制完成后的回调事件
                $('#stockGoodsTable td .fa-chevron-down')
                    .on(
                        'click',
                        function(event) {
                            event.stopPropagation();

                            var tr = $(this).closest("tr");
                            row = $stockGoodsTable.row(tr);

                            if (row.child.isShown()) {
                                row.child.hide();
                                tr.removeClass('shown');
                                $(this).removeClass('fa-chevron-up');
                                $(this).addClass('fa-chevron-down');
                            } else {
                                // 关闭其他
                                $('#stockGoodsTable tbody tr').each(function() {
                                    if ($(this).attr("role") == "row") {
                                        $stockGoodsTable.row($(this)).child.hide();
                                    }
                                });

                                $('.fa-chevron-up', $('#stockGoodsTable tbody')).addClass('fa-chevron-down');
                                $('.fa-chevron-down', $('#stockGoodsTable tbody')).removeClass('fa-chevron-up');

                                var goodsId = row.data().goodsId;
                                var ifmSrc = "/views/warehouse/stockGoodsCheck/stockGoodsDetail.html?goodsId=" + goodsId;
                                var swidth = $("div.tab-content").width() - 30;
//                                                var swidth = "100%";
                                var sheight = "380";
                                var temp = '<iframe myid="" tab="" shopType="" id="contentFrame1" name="contentFrame" style="width:'+swidth+'px" frameborder="0" scrolling="auto" src="'
                                    + ifmSrc + '" height="'+(sheight-20)+'"></iframe>';
                                row.child(temp).show();
                                tr.addClass("shown");
                                $("#myid").val(goodsId);
                                $contentIframe = tr.find("iframe").eq(0);

                                $(this).addClass('fa-chevron-up');
                                $(this).removeClass('fa-chevron-down');
                            }
                            return false;
                        });
            });

    // 文字过长截断显示悬浮框
    $("#stockGoodsTable").tooltip({
        selector: ".tooltip-column-detail",
        container: "body",
        title: function() {
            if ($(this)[0].scrollWidth > $(this).outerWidth()) {
                return $(this).text();
            }
        }
    });
};



// 查询数据
stockGoodsList.queryTableData = function() {
    var queryData = $("#advSearchPanel").data("queryData");
    if (null == $stockGoodsTable) {
        stockGoodsList.initStockGoodsTable();
    } else {
        var optionData = $stockGoodsTable.settings()[0].ajax.data;
        if (optionData.formJson) {
            optionData.formJson = encodeURI(JSON.stringify($.extend(true, {}, $.parseJSON(optionData.formJson), $.parseJSON(queryData))));
        }
        optionData.quickSearch = encodeURI($("#quickSearch").val());
        optionData.queryStatus = encodeURI($("#quickSearch").data("queryStatus"));

        $stockGoodsTable.settings()[0].ajax.data = optionData;
        $stockGoodsTable.ajax.reload();
    }
};


/*
 * 刷新系统退款单列表
 */
function refresh() {
    refreshCheck();
    drawTable();
}
function refreshCheck(){
    $('#quickSearch').val("");
    searchCondition = {};
    stockGoodsList.queryTableData();
}



// 设置时间区间，用于区间的初始化和区间控件选择后的回调
stockGoodsList.setdaterange = function(start, end) {
    if(!start||!end){
        $('.reportrange span').html("请选择时间区间");
        $('input[name="datestart"]').val("");
        $('input[name="dateend"]').val("");
    }else{
        $('.reportrange span').html(start.format('YYYY-MM-DD') + ' - ' + end.format('YYYY-MM-DD'));
        $('input[name="datestart"]').val(start.format("YYYY-MM-DD"));
        $('input[name="dateend"]').val(end.format("YYYY-MM-DD"));
    }

};

var tableColNm=[];		//画面table的头的项目名称
var tableColVal=[];		//画面table的头的项目名称对应的英文字段

function showExportStock() {
        tableColNm=new Array();
        tableColVal=new Array();

        $("#public-methods").html('');
        if ("p"==$("#storSelect").val()){
            $("#public-methods").append('<option value="goodsCode">商品商家编码</option>');
            $("#public-methods").append('<option value="goodsName">商品名称</option>');
            $("#public-methods").append('<option value="totalQty">本地总库存数</option>');
            $("#public-methods").append('<option value="stockQty">本地合格品数</option>');
            $("#public-methods").append('<option value="available">可用数</option>');
            $("#public-methods").append('<option value="canallotQty">可分派数</option>');
            $("#public-methods").append('<option value="allotQty">已分派数</option>');
            $("#public-methods").append('<option value="unallotQty">未分派数</option>');
            $("#public-methods").append('<option value="logicStockoutQty">逻辑出库数</option>');
            $("#public-methods").append('<option value="onwayQty">在途数</option>');
            $("#public-methods").append('<option value="reserveQty">预留数</option>');
            $("#public-methods").append('<option value="junkQty">废品数</option>');
            $("#public-methods").append('<option value="totalCount">第三方总库存数</option>');
            $("#public-methods").append('<option value="sellCount">第三方可销售库存数</option>');
            $("#public-methods").append('<option value="junkCount">第三方废品数</option>');
        } else {
            $("#public-methods").append('<option value="goodsCode">商品商家编码</option>');
            $("#public-methods").append('<option value="goodsName">商品名称</option>');
            $("#public-methods").append('<option value="storName">仓库名称</option>');
            $("#public-methods").append('<option value="totalQty">本地仓库总库存数</option>');
            $("#public-methods").append('<option value="stockQty">本地仓库正品数</option>');
            $("#public-methods").append('<option value="junkQty">本地仓库次品数</option>');
            $("#public-methods").append('<option value="available">本地仓库可用数</option>');
            $("#public-methods").append('<option value="allotQty">本地仓库已分派数</option>');
            $("#public-methods").append('<option value="unallotQty">本地仓库未分派数</option>');
            $("#public-methods").append('<option value="logicStockoutQty">本地仓库逻辑出库数</option>');
            $("#public-methods").append('<option value="onwayQty">本地仓库在途数</option>');
            $("#public-methods").append('<option value="reserveQty">本地仓库预留数</option>');

            $("#public-methods").append('<option value="extTotalCount">第三方仓库总库存数</option>');
            $("#public-methods").append('<option value="extstorStockCount">第三方仓库正品数</option>');
            $("#public-methods").append('<option value="extstorJunkCount">第三方仓库次品数</option>');
            $("#public-methods").append('<option value="extstorSellCount">第三方仓库可销售数</option>');
            $("#public-methods").append('<option value="extstorAvailable">第三方仓库可用数</option>');
            $("#public-methods").append('<option value="extstorAllotQty">第三方仓库已分派数</option>');
            $("#public-methods").append('<option value="extstorUnallotQty">第三方仓库未分派数</option>');
            $("#public-methods").append('<option value="extstorCanallotQty">第三方仓库可分派数</option>');
            $("#public-methods").append('<option value="extstorOnwayQty">第三方仓库在途数</option>');
            $("#public-methods").append('<option value="extstorReserveQty">第三方仓库预留数</option>');
        }

    $("#public-methods option").each(function (){
        tableColNm.push($(this).text());
        tableColVal.push($(this).val());
    });

        //刷新隐藏的select项目，将新的option显示到画面上
        $("#refresh").click();

        //清空frame的SRC，相当于重置
        $('#exportFrame').attr('src', '');
        var editDialog = window.top.window.borrowCustomModalDialog($("#exportList"));
        editDialog.modal({show:true, backdrop:'static'});

}

function exportStock(){
    var url = "";

    // 父窗体归还本页的编辑对话框
    window.top.window.returnCustomModalDialog();

    //画面中选择的需要导出的项目的名字,对应的英文名字
    var selectColNm=new Array();
    var selectColVal=new Array();
    var colNm;
    //根据画面选择，抽取相应的字段名称，汉字
    $('#ms-public-methods .ms-selectable .ms-list li').each(function(){
        if ($(this).attr('class') && $(this).attr('class').indexOf('ms-selected')>-1){
            colNm = $(this).text();
            $.each(tableColNm,function(key,val){
                if (val == colNm){
                    selectColNm.push(val);
                    selectColVal.push(tableColVal[key]);
                }
            });
        }
    });

    //传递参数
    var colName = encodeURI(encodeURI(selectColNm.join(',')));
    var colValue = encodeURI(encodeURI(selectColVal.join(',')));
    var quickSearch = encodeURI(encodeURI($('#quickSearch').val()));

    //如果没有选择项目，给出提示
    if (colName==''){
        window.top.window.showModalAlert("请选择导出项目。");
        window.top.window.borrowCustomModalDialog($("#exportList"));
        return false;
    }

    var storType = $("#storSelect").val()
    $.ajax({
        type: 'GET',
        url: "/stockGoods/exportCheckStock.action",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        async: false,//同步
        success: function (data) {
            if (data.result == "success") {
                $('#exportList').modal('hide');
                //导出的URL
                url = "/stockGoods/exportStock.action?colName="+colName+"&colValue="+colValue+"&quickSearch="+quickSearch+"&storType="+storType;
                $('#exportFrame').attr('src', url);
                return true;
            } else {
                window.top.window.showModalAlert(data.msg);
                window.top.window.borrowCustomModalDialog($("#exportList"));
                return false;
            }
        },
        error: function () {
            window.top.window.showModalAlert("导出失败。");
            window.top.window.borrowCustomModalDialog($("#exportList"));
            return false;
        }
    });

}